package com.jinx.demo_log.controller;

import com.jinx.demo_log.domain.SysOperLog;
import com.jinx.demo_log.domain.User;
import com.jinx.demo_log.page.CustomPage;
import com.jinx.demo_log.service.MongoDBService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping(value = "/mongo")
public class MongoController {
    @Autowired
    private MongoDBService mongoDBService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @PostMapping(value = "/add")
    public Object add(@RequestBody User user){
        ArrayList<User> users = new ArrayList<>();
        users.add(user);
        mongoDBService.add(users,"jinxuser");
        return "success";
    }

    @GetMapping(value = "/search")
    public Object search(String key){
        Query query = new Query();
        query.addCriteria(Criteria.where("uniqueKey").is(key));
        List<SysOperLog> list = mongoDBService.findList(query, "jinxuser");
        return list;
    }

    @GetMapping(value = "/page")
    public Object page(int pageNum,int pageSize,String keyWord){
        Query query = new Query();
        if (Objects.nonNull(keyWord)) {
            query.addCriteria(Criteria.where("uniqueKey").is(keyWord));
        }
        long totalCount = mongoTemplate.count(query, "jinxLog");
        query = query.limit(pageSize).skip((pageNum - 1) * pageSize);
        query = query.with(Sort.by(Sort.Order.desc("operTime")));
        List<SysOperLog> jinxuser = mongoTemplate.find(query, SysOperLog.class, "jinxLog");
        CustomPage<SysOperLog> page = new CustomPage<>();
        page.setRows(jinxuser);
        page.setRecords(totalCount);
        page.setPage(pageNum);
        page.setPagesize(pageSize);
        page.setTotal((page.getRecords() + pageSize - 1) / pageSize);
        page.setOrderByField("operTime");
        return page;
    }

}
